package persistence;

import java.util.Properties;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.event.LoadEventListener;
import org.hibernate.stat.EntityStatistics;
import org.hibernate.stat.Statistics;

import auction.chapter12.MyLoadEventListener;

public class HibernateUtil
{
	private static SessionFactory sessionFactory;
	private static SessionFactory sessionFactory2;
	private static Configuration cfg;
	
	static
	{
		try
		{
			//sessionFactory=new Configuration().configure("hibernate_hsql.cfg.xml").buildSessionFactory();
			cfg=new Configuration();
			LoadEventListener[] listenerStack={ new MyLoadEventListener() };
			//Must before call .configure(...)
			//cfg.getEventListeners().setLoadEventListeners(listenerStack);
			
			cfg.configure("hibernate_mysql.cfg.xml");
			//cfg.configure("hibernate_mssql.cfg.xml");
			sessionFactory=cfg.buildSessionFactory();
			
			
			
			//sessionFactory2=new Configuration().configure("hibernate_mysql2.cfg.xml").buildSessionFactory();
			
			Statistics stats=sessionFactory.getStatistics();
			stats.setStatisticsEnabled(true);
		}catch(Throwable ex)
		{
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	public static SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}
	
	public static SessionFactory getSessionFactory2()
	{
		return sessionFactory2;
	}
	
	public static void shutdown()
	{
		//close caches and connection pools
		getSessionFactory().close();
	}
	
	static void out(Object obj) {
		System.out.println("--->" + obj);
	}
	
	public static void props(){
		Properties p=cfg.getProperties();
		Set<Object> keys=p.keySet();
		for(Object key : keys){
			out(key+"="+p.get(key));
		}
	}
	
	public static void stat()
	{
		Statistics stats=sessionFactory.getStatistics();
		stats.logSummary();
		
		EntityStatistics msgStats=stats.getEntityStatistics("hello.Message");
		System.out.println("hello.Message fetch count--"+msgStats.getFetchCount());
	}
}